package com.xuecheng.learning.listener;

import com.alibaba.fastjson.JSON;
import com.xuecheng.api.learning.model.dto.CourseRecordDTO;
import com.xuecheng.api.order.model.dto.OrdersDTO;
import com.xuecheng.api.order.model.vo.PayResultModel;
import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.learning.common.constant.LearningErrorCode;
import com.xuecheng.learning.service.CourseRecordService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

@Component
@RocketMQMessageListener(consumerGroup = "consumer_group_record_azhen", topic = "${order.pay.topic.azhen}")
public class ConsumerTxmsgLearningListener implements RocketMQListener<String> {

    @Autowired
    private CourseRecordService courseRecordService;

    @Override
    public void onMessage(String jsonString) {
        // 1.获得消息,并解析
        PayResultModel payResultModel = JSON.parseObject(jsonString, PayResultModel.class);
        OrdersDTO ordersDTO = payResultModel.getOrder();

        if (ObjectUtils.isEmpty(ordersDTO))
            ExceptionCast.cast(LearningErrorCode.E_202203);


        // 2.调用service创建或者用户的学习记录
        CourseRecordDTO recordDTO = new CourseRecordDTO();

        recordDTO.setUserName(ordersDTO.getUserName());
        recordDTO.setCoursePubId(ordersDTO.getCoursePubId());

        this.courseRecordService.createOrModifyRecord(recordDTO);
    }
}
